package indi.mozping.mozping.redission;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.CountDownLatch;

/**
 * @author by mozping
 * @Classname RedissionTest
 * @Description 分布式锁示例，通过分布式锁操作count变量
 * @Date 2020/9/9 10:22
 */
public class RedissionRedLockTest {

    /**
     * config const
     */
    private static int count = 0;
    private static final int SCAN_INTERVAL = 2000;
    private static final String[] REDIS_ADDRESS = new String[]{
            "redis://192.168.11.73:7001"
    };
    private static final String LOCK_NAME = "myLock";

    private static RLock lock;

    static {
        Config config = new Config();
        config.useClusterServers().setScanInterval(SCAN_INTERVAL).addNodeAddress(REDIS_ADDRESS);
        /**
         * variable
         */
        RedissonClient redission = Redisson.create(config);
        lock = redission.getLock(LOCK_NAME);
    }

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static CountDownLatch mainCountDownLatch = new CountDownLatch(20);

    public static void main(String[] args) throws InterruptedException {

        final Thread[] threads = new Thread[20];

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(new Runnable() {
                public void run() {
                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    for (int j = 0; j < 100; j++) {
                        lock.lock();
                        try {
                            System.out.println("加锁后执行..." + Thread.currentThread().getName());
                            count++;
                        } finally {
                            lock.unlock();
                        }
                    }
                    mainCountDownLatch.countDown();
                }
            });
        }

        //启动线程
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        //线程起跑
        countDownLatch.countDown();
        mainCountDownLatch.await();
        Thread.sleep(1000);
        System.out.println("End ... " + count);
        System.exit(0);
    }
}